package com.edt.ichannel.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class SignMsgUtil {

	private static Logger logger = LogManager.getLogger(SignMsgUtil.class);
	
	/**
	 * 过滤无用参数,包括参数值为空及制定参数signMsg
	 * @author guodong
	 * @date 2016年12月28日
	 * @param params Map 带过滤的参数
	 * @return Map 过滤后的参数
	 * 
	 */
	private static Map<String, String> filterNoParams(Map<String, String> params) {
		Map<String, String> newParam = new HashMap<String, String>();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			if ("signMsg".equalsIgnoreCase(key) ) {
				continue;
			}
			if (value == null||value.length()==0) {
				continue;
			}
			newParam.put(key, value);
		}
		return newParam;
	}
	
	private static String createJsonString(Map<String, String> params) {
		String signSource ="";
		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			signSource+= (key+"="+params.get(key)+"&");
		}
		return signSource;
	}
	
	/**
	 * 待签名参数预处理，去空、排序、加密
	 * @author guodong
	 * @date 2016年12月28日
	 * @param params 传入参数Map
	 * @return 真实参与签名的参数串
	 */
	private static String getSignSourMsg(Map<String, String> params) {
		params = filterNoParams(params);
		String signSource = createJsonString(params);
		logger.info("待签名参数串：[" + signSource+"]");
		return signSource;
	}
	
	/**
	 * 生成签名：
	 * @param params 传入参数Map
	 * @param sing	传入密钥
	 * @return	返回加密串
	 */
	public static String getSignMsg(Map<String, String> params,String sing) {
		logger.info("加密串:"+getSignSourMsg(params)+sing);
		return MD5.getMD5(getSignSourMsg(params)+sing);
	}


	public static String getToken(Map<String, String> params,String secret) {
		StringBuilder signSource = new StringBuilder();
		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);
		for (String key : keys) {
			signSource.append(key).append(params.get(key));
		}
		logger.info(signSource+secret);
		return MD5.getMD5(signSource+secret);
	}
}

